import { Card, Form, Select, Col, Button, Table, Popconfirm, message, Tag, Input } from "antd";
import { PlusOutlined, WalletFilled, DeleteFilled } from "@ant-design/icons"
import { useEffect, useRef, useState } from "react";

//类型
import type {
    attrListReturnType,
    attrListReturnItemType,
    cateGory1ListType,
    cateGory2ListType,
    cateGory3ListType,
    attrValueItemType,
    addOrEditAttrParamsType
} from "@/api/product/model/attrType"
//api
import {
    deleteAttr,
    requestAttrList,
    requestCategory1List,
    requestCategory2List,
    requestCategory3List,
    addOrEditAttr
} from "@/api/product/attr";
//nanoid
// import {nanoid} from ""

export default function Attr() {
    //定义表格数据
    const [tableData, settableData] = useState<attrListReturnType>([])
    //定义三级分类数据
    const [category1list, setCategory1list] = useState<cateGory1ListType>([])
    const [category2list, setCategory2list] = useState<cateGory2ListType>([])
    const [category3list, setCategory3list] = useState<cateGory3ListType>([])
    //保存3Id
    const [category3Id, setCategory3Id] = useState<number>(0)
    //定义数据条件渲染
    const [isShowCard, setIsShowCard] = useState<boolean>(true)


    //定义数据保存修改或新增请求的参数 (添加或修改请求的参数)
    const [attrValueData, setAttrValueData] = useState<addOrEditAttrParamsType>({
        id: 0,
        attrName: "",
        categoryId: category3Id,
        categoryLevel: 3,
        attrValueList: []
    })
    //保存临时id
    const [tempId, setTempId] = useState<number>()
    //保存旧值
    const [oldValue, setOldValue] = useState<string>()

    //获取表单实例
    const [form] = Form.useForm()
    const [form1] = Form.useForm()


    //初始化请求一级分类
    useEffect(() => {
        //初始请求一级分类列表
        getCategory1list();

    }, [])

    //监听3Id改变 提交表单(请求平台属性列表)
    useEffect(() => {
        //初始不执行
        if (!category3Id) return
        //提交表单
        form.submit()
    }, [category3Id])


    //1.请求一级分类数据 (初始化调用)
    const getCategory1list = async () => {
        await requestCategory1List()
            .then((res) => setCategory1list(res))
            .catch((e) => { message.error(e) })
    }

    //2.请求二级分类数据 (根据1Id)
    const getCategory2list = async (value: number) => {
        //先清空二级 三级 的数据
        form.setFieldsValue({ category2Id: null, category3Id: null })

        await requestCategory2List(value)
            .then((res) => setCategory2list(res))
            .catch((e) => { message.error(e) })
    }

    //3.请求三级分类数据 (根据2Id)
    const getCategory3list = async (value: number) => {
        //先清空三级 的数据
        form.setFieldsValue({ category3Id: null })

        await requestCategory3List(value)
            .then((res) => setCategory3list(res))
            .catch((e) => { message.error(e) })
    }

    //4.请求平台属性数据 (提交表单触发)
    const getAttrList = async (value: any) => {
        //请求平台属性列表
        await requestAttrList(value)
            .then((res) => settableData(res))
            .catch((e) => message.error(e))
    }

    //5.删除平台属性
    const deleteAttrHandel = (id: number) => {
        return async () => {
            await deleteAttr(id)
                .then(() => { form.submit(); message.success("删除成功!") })
                .catch(() => message.error("删除失败!"))
        }
    }

    //6.点击新增平台属性(清空)
    const addAttr = () => {
        //展示新增修改页
        setIsShowCard(false)

        //清空上次数据(清空不需要的，保留固定发送的)
        setAttrValueData({
            ...attrValueData,
            id: 0,
            attrName: "",
            attrValueList: []
        })

        //清空表单
        form1.setFieldsValue({ attrName: null })
    }

    //7.点击修改平台属性(回填)
    const editAttr = (data: attrListReturnItemType) => {
        return () => {
            //展示新增修改页
            setIsShowCard(false)
            //回填参数数据
            setAttrValueData(data)

            //把属性名填充到表单
            form1.setFieldsValue({ attrName: data.attrName })
        }
    }


    //8.添加属性值(push)
    const addAttrValue = () => {
        //创建一条新的属性值数据(默认是编辑模式)
        const valueData = {
            id: Date.now(),
            valueName: "",
            isEdit: true
        }
        //添加到数组
        const newAttrValueList = attrValueData.attrValueList.map((item) => item)
        newAttrValueList.push(valueData)

        //保存新添加的临时id(为了监听到新的input)
        setTempId(valueData.id)

        //修改状态 更新视图
        setAttrValueData({
            ...attrValueData,
            attrValueList: newAttrValueList,
        })
    }

    //9.切换到编辑模式(修改isEdit)
    const changeToEdit = (data: attrValueItemType) => {
        return () => {
            //保存临时Id
            setTempId(data.id)
            //保存旧值
            setOldValue(data.valueName)

            //修改当前数据的isEdit
            const newattrValueList = attrValueData.attrValueList.map((item) => {
                return item.id === data.id ? { ...item, isEdit: true } : { ...item }
            })

            //修改状态 更新视图
            setAttrValueData({
                ...attrValueData,
                attrValueList: newattrValueList
            });
        }
    }

    //10.属性值输入框改变的回调
    const changeInput = (e: any) => {


        //获取输入框的值 修改数据
        const newattrValueList = attrValueData.attrValueList.map((item) => {
            return item.id === tempId ? { ...item, valueName: e.target.value } : { ...item }
        })

        //修改状态 更新视图
        setAttrValueData({
            ...attrValueData,
            attrValueList: newattrValueList
        })
    }

    //11.切换到查看模式(修改isEdit)
    const changeToLook = (data: attrValueItemType) => {
        return () => {
            //判断重复(不能和自己比较)
            const isRepect = attrValueData.attrValueList.some(item => item.valueName === data.valueName && item.id !== data.id)

            //输入为空
            if (!data.valueName) {
                //判断有无旧值
                if (oldValue) {
                    //有旧值就恢复 并切回查看模式
                    const attrValueList = attrValueData.attrValueList.map((item) => {
                        return item.id === data.id ? { ...item, valueName: oldValue, isEdit: false } : { ...item }
                    })
                    setAttrValueData({ ...attrValueData, attrValueList })

                    //清空旧值(一定)
                    setOldValue("")

                    return
                } else {
                    //没有旧值 说明用户添加了一个空值 删除
                    const attrValueList = attrValueData.attrValueList.filter((item) => {
                        return item.id !== data.id
                    })
                    setAttrValueData({ ...attrValueData, attrValueList })

                    return
                }
            }

            //输入重复
            if (isRepect) {
                //判断有无旧值
                if (oldValue) {
                    //有旧值就恢复 并切回查看模式
                    const attrValueList = attrValueData.attrValueList.map((item) => {
                        return item.id === data.id ? { ...item, valueName: oldValue, isEdit: false } : { ...item }
                    })
                    setAttrValueData({ ...attrValueData, attrValueList })

                    //清空旧值(一定)
                    setOldValue("")

                    return
                } else {
                    //没有旧值 说明用户添加了重复的值 还是删除
                    const attrValueList = attrValueData.attrValueList.filter((item) => {
                        return item.id !== data.id
                    })
                    setAttrValueData({ ...attrValueData, attrValueList })

                    return
                }
            }

            //正常切换为查看模式
            const attrValueList = attrValueData.attrValueList.map((item) => {
                return item.id === data.id ? { ...item, isEdit: false } : { ...item }
            })
            setAttrValueData({ ...attrValueData, attrValueList })

            //清空旧值(一定)
            setOldValue("")
        }
    }

    //12.删除属性值
    const deleteValue = (id: number) => {
        return () => {
            //过滤掉当前项 得到新数组
            const attrValueList = attrValueData.attrValueList.filter((item) => {
                return item.id !== id
            })
            //修改状态 更新视图
            setAttrValueData({ ...attrValueData, attrValueList })
        }
    }

    //13.保存
    const save = async () => {
        //收集请求体参数 发送修改或新增请求
        await addOrEditAttr(attrValueData)
            .then(() => {
                //切换页面
                setIsShowCard(true)
                //重新请求属性值列表
                form.submit()
                //成功提示
                message.success(attrValueData.id ? '修改成功!' : '添加成功!')
            })
            .catch((e) => { message.error(e) })
    }


    //平台属性列数据配置
    const attrListColumns = [
        {
            title: '序号',
            width: 120,
            align: "center" as "center",
            render(_: any, __: any, index: number) {
                return index + 1
            }
        },
        {
            title: '属性名称',
            dataIndex: 'attrName',
        },
        {
            title: '属性值列表',
            render(_: any, data: attrListReturnItemType) {
                return (
                    <div>
                        {data.attrValueList.map((item) => {
                            return <Tag color="green" key={item.id}>{item.valueName}</Tag>
                        })}
                    </div>
                )
            }
        },
        {
            title: '操作',
            width: 300,
            render(_: any, data: attrListReturnItemType) {
                return (
                    <div>
                        <Button onClick={editAttr(data)} type="primary" style={{ marginRight: '10px' }} icon={<WalletFilled />}>修改</Button>

                        <Popconfirm
                            title="是否要删除?"
                            onConfirm={deleteAttrHandel(data.id)}
                            onCancel={() => message.warning("已取消删除")}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button type="primary" danger={true} style={{ marginRight: '10px' }} icon={<DeleteFilled />}>删除</Button>
                        </Popconfirm>

                    </div>
                )
            }
        },
    ];

    //属性值列数据配置
    const attrValueListColumns = [
        {
            title: '序号',
            width: 120,
            align: "center" as "center",
            render(_: any, __: any, index: number) {
                return index + 1
            }
        },
        {
            title: '属性值名称',
            render(_: any, data: attrValueItemType) {
                return (
                    <div>
                        {
                            data.isEdit ?
                                <Input
                                    type="text"
                                    onBlur={changeToLook(data)}
                                    onChange={changeInput}
                                    value={data.valueName}
                                    autoFocus
                                ></Input> :
                                <span onClick={changeToEdit(data)} >{data.valueName}</span>
                        }
                    </div>
                )
            }
        },
        {
            title: '操作',
            width: 300,
            render(_: any, data: attrValueItemType) {
                return (
                    <Popconfirm
                        title="是否要删除?"
                        onConfirm={deleteValue(data.id as number)}
                        onCancel={() => message.warning("已取消删除")}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button type="primary" danger={true} style={{ marginRight: '10px' }} icon={<DeleteFilled />}>删除</Button>
                    </Popconfirm>
                )
            }
        },
    ]

    return (
        <div>
            {/* 三级列表页 */}
            <Card style={{ margin: '30px' }}>
                <Form
                    layout="inline"
                    form={form}
                    onFinish={getAttrList}
                >
                    <Col span={7}>
                        <Form.Item label="一级分类" name="category1Id">
                            <Select
                                disabled={!isShowCard}
                                placeholder="请选择"
                                onChange={getCategory2list}
                            >
                                {category1list.map((item) => {
                                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>

                    <Col span={7}>
                        <Form.Item label="二级分类" name="category2Id">
                            <Select
                                disabled={!isShowCard}
                                placeholder="请选择"
                                onChange={getCategory3list}
                            >
                                {category2list.map((item) => {
                                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>

                    <Col span={7}>
                        <Form.Item label="三级分类" name="category3Id">
                            <Select
                                disabled={!isShowCard}
                                placeholder="请选择"
                                onChange={(value: number) => setCategory3Id(value)}
                            >
                                {category3list.map((item) => {
                                    return <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                })}
                            </Select>
                        </Form.Item>
                    </Col>
                </Form>
            </Card>

            {!isShowCard ?
                //修改添加页
                <Card style={{ margin: '30px' }}>
                    <Form form={form1}>
                        <Col span={6}>
                            <Form.Item label="属性名" name="attrName">
                                <Input
                                    placeholder="请输入属性名"
                                    onChange={(e) => setAttrValueData({ ...attrValueData, attrName: e.target.value })}
                                />
                            </Form.Item>
                        </Col>

                        <Form.Item>
                            <Button
                                onClick={addAttrValue}
                                disabled={!attrValueData.attrName}
                                type="primary"
                            >添加属性值</Button>
                            <Button
                                onClick={() => setIsShowCard(true)}
                                style={{ marginLeft: '20px' }}
                            >取消</Button>
                        </Form.Item>

                        <Form.Item>
                            <Table
                                dataSource={attrValueData.attrValueList}
                                columns={attrValueListColumns}
                                bordered={true}
                                rowKey="id"
                                pagination={false}
                            />
                        </Form.Item>

                        <Form.Item>
                            <Button
                                type="primary"
                                onClick={save}
                                disabled={!attrValueData.attrName || attrValueData.attrValueList.length === 0}
                            >保存</Button>
                            <Button onClick={() => setIsShowCard(true)} style={{ marginLeft: '20px' }}>取消</Button>
                        </Form.Item>
                    </Form>
                </Card> :

                //平台属性页 
                <Card
                    title={<Button disabled={!category3Id} onClick={addAttr} type="primary" icon={<PlusOutlined />}>新增属性</Button>}
                    style={{ margin: '30px' }}
                >
                    <Table
                        dataSource={tableData}
                        columns={attrListColumns}
                        bordered={true}
                        rowKey="id"
                        pagination={false}
                    />
                </Card>
            }
        </div >
    )
}
